var app = getApp();
/**
 * 微信支付--order_id
 */
function wxPayMoneyByOrderid(order_id, success, fail) {
  app.Ajax({
    method: 'POST',
    url: '/api/index.php?app=payment&act=store',
    data: {
      order_id: order_id,
    },
    success: (res) => {
      var payment_id = res.id;
      wxPayMoneyById(payment_id, success, fail);
    }
  })
}

/**
 * 微信支付--payment_id
 */
var isPaying = false;
function wxPayMoneyById(payment_id, success, fail) {
  if (isPaying) {
    return;
  }
  isPaying = true;  //正在支付中...

  app.Ajax({
    url: '/api/index.php?app=payment&act=prepayParams',
    data: {
      payment_id: payment_id,
    },
    success: function (res) {
      wx.requestPayment({
        'timeStamp': res.timestamp,
        'nonceStr': res.nonceStr,
        'package': res.package,
        'signType': res.signType,
        'paySign': res.paySign,
        'success': function (res) {
          checkOrderStatus(payment_id, (res) => {
            isPaying = false;
            typeof success == "function" && success()
          }, (err) => {
            isPaying = false;
            typeof fail == "function" && fail()
          })
        },
        'fail': function (res) {
          isPaying = false;
          typeof fail == "function" && fail()
        }
      })

      if (isPaying) {
        setTimeout(() => {
          isPaying = false;
        }, 3000);
      }
    },
    fail: (err, code) => {
      isPaying = false;
      typeof fail == "function" && fail(err, code)
    }
  });
}

var checkInterval;
function checkOrderStatus(payment_id, success, fail) {
  var check_num = 5;
  clearInterval(checkInterval);
  checkInterval = setInterval(() => {
    app.Ajax({
      url: '/api/index.php?app=payment&act=show',
      data: {
        payment_id: payment_id
      },
      success: (res) => {
        if (res.status == 'paid') {
          clearInterval(checkInterval);
          typeof success == "function" && success()
        }
      }
    });
    check_num -= 1;
    if (check_num == 0) {
      clearInterval(checkInterval);
      typeof fail == "function" && fail()
    }
  }, 1000);
}

module.exports = {
  wxPayMoneyById: wxPayMoneyById,
  wxPayMoneyByOrderid: wxPayMoneyByOrderid,
}
